package cn.pink.gamesrv.human.module.group;

import cn.pink.common.entity.game.group.EntityHumanGroup;
import cn.pink.common.proto.Msg;
import cn.pink.core.support.Log;
import cn.pink.gamesrv.human.HumanObject;
import cn.pink.gamesrv.human.module.IMod;
import cn.pink.logicsrv.RPCProxy;
import com.google.protobuf.GeneratedMessageV3;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 玩家群
 */
public class ModGroup implements IMod {
    HumanObject humanObj;

    EntityHumanGroup humanGroupDB;

    public ModGroup(HumanObject humanObj) {
        this.humanObj = humanObj;
    }

    public void load(Map<String, Object> data) {
        if(data == null) {
            humanGroupDB = (EntityHumanGroup) humanObj.createEntityProxy(EntityHumanGroup.class).getEntity();
        }
        else {
            humanGroupDB = (EntityHumanGroup) humanObj.createAndInitEntityProxy(EntityHumanGroup.class, data).getEntity();
        }
    }

    @Override
    public void afterReadData() {

    }

    @Override
    public void loginFinish() {

    }

    @Override
    public GeneratedMessageV3 build2ClientData() {
        return null;
    }

    /**
     * 创建玩家群
     */
    public void createGroup(String name, String notice, int headId, int apply, int requireLv) {
        if(hasGroup()) {
            Log.game.error("createGroup hasGroup, humanId={}", humanObj.getId());
            return;
        }

        RPCProxy.GroupServiceProxy proxy = RPCProxy.GroupServiceProxy.newInstance();
        proxy.createGroup(humanObj.getId(), name, notice, headId, apply, requireLv);

        proxy.listenResult((result, context) -> {
            long groupId = result.getLong();

            if(groupId <= 0) {
                //TODO sendHint
                return;
            }

            Set<Long> history = humanGroupDB.getHistory() == null ? new HashSet<>() : humanGroupDB.getHistory();
            history.add(groupId);

            humanGroupDB.setGroupId(groupId);
            humanGroupDB.setHistory(history);

            Msg.SCCreateGroup.Builder msg = Msg.SCCreateGroup.newBuilder();
            msg.setGroupId(groupId);

            humanObj.sendMsg(msg);
        });
    }

    public void joinGroup(long groupId) {
        if(hasGroup()) {
            Log.game.error("joinGroup hasGroup, humanId={}", humanObj.getId());
            return;
        }

        RPCProxy.GroupServiceProxy proxy = RPCProxy.GroupServiceProxy.newInstance();
        proxy.joinGroup(humanObj.getId(), groupId);

        proxy.listenResult((result, context) -> {
            System.out.println(result);
        });
    }

    private boolean hasGroup() {
        return humanGroupDB.getGroupId() > 0L;
    }
}
